package com.stenio.fancat.service.baby;

import com.stenio.fancat.domain.baby.FcBehaviorImage;
import com.stenio.fancat.mapper.baby.FcBehaviorImageMapper;
import com.stenio.fancat.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author liuan
 * @create 2019-01-16 20:32
 */
@Service
public class BehaviorImageService {

    @Autowired
    private FcBehaviorImageMapper fcBehaviorImageMapper;

    @Autowired
    private OssService ossService;

    @Value("${oss.piggybank.endpoint}")
    private String piggybankEndPoint;
    /**
     * 保存图片
     * @param file
     * @return
     */
    public FcBehaviorImage saveImage(MultipartFile file){
        FcBehaviorImage image = new FcBehaviorImage();
        Date date = new Date();
        image.setCreateTime(date);
        image.setUpdateTime(date);
        try {
            String fileName = getImageName(file.getOriginalFilename());
            image.setUrl(piggybankEndPoint+fileName);
            ossService.putObject(fileName,file.getBytes());
            fcBehaviorImageMapper.insert(image);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    private String getImageName(String sourceName){
        StringBuffer sb = new StringBuffer();
        sb.append(UUID.randomUUID().toString());
        sb.append(sourceName.substring(sourceName.lastIndexOf(".")));
        return sb.toString();
    }

    /**
     * 将图片和业务id进行关联
     * @param bId
     * @param imageId
     */
    public void updateBiz(String bId, Integer imageId){
        FcBehaviorImage image = new FcBehaviorImage();
        image.setId(imageId);
        image.setBehaviorId(bId);
        fcBehaviorImageMapper.updateBiz(image);
    }

    public List<FcBehaviorImage> selectByType(FcBehaviorImage image){
        return fcBehaviorImageMapper.selectByType(image);
    }

    public void deleteById(Integer id){
        fcBehaviorImageMapper.deleteById(id);
    }

}
